package ginv

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"reflect"
	"time"
)

var (
	typeContext    = reflect.TypeOf(new(context.Context)).Elem()
	typeError      = reflect.TypeOf(new(error)).Elem()
	defaultContext = &gin.Context{}
	DefaultGinTime = 10 * time.Second
	ctx            = context.Background()
)

const RequestId = "requestId"

func GetGin(ctx context.Context) *gin.Context {
	return defaultContext
}

func GetCtx(ctxs context.Context) context.Context {
	ctx, cancel := context.WithTimeout(ctx, DefaultGinTime)
	defer cancel()
	return ctx
}

func GinSet(ctx context.Context, key string, value any) {
	defaultContext.Set(key, value)
}

func GinGet(ctx context.Context, key string) (value any, exists bool) {
	value, exists = defaultContext.Get(key)
	return
}

func inparam(c *gin.Context, reqs reflect.Type) (reflect.Value, error) {
	var bs []binding.Binding
	b := binding.Default(c.Request.Method, c.ContentType())
	if b == binding.Form {
		bs = []binding.Binding{b, binding.Header}
	} else {
		bs = []binding.Binding{b, binding.Header, binding.Form}
	}
	reqV := reflect.New(reqs)
	req := reqV.Interface()
	for _, b := range bs {
		err := c.ShouldBindWith(req, b)
		if err != nil {
			return reqV, err
		}
	}
	err := c.ShouldBindUri(req)
	if err != nil {
		return reflect.Value{}, err
	}
	return reqV, nil
}

